package service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import object.Tour;

public class FileService 
{
	private File workFile;
	
	private final String defaultFileName = "defaultData.txt";
	
	public FileService()
	{
	}
	
	public boolean checkFile(String[] args, List<Tour> list)
	{
		if (args.length == 0)
		{
			workFile = new File(defaultFileName);
			return loadFile(list);
		}
		else
		{
			workFile = new File(args[0]);
			
			if (workFile.isFile() && workFile.exists())
			{
				return loadFile(list);
			}
			else if (workFile.isDirectory())
			{
				try
				{
					String fileName = workFile.getAbsolutePath() + "\\" + defaultFileName;
					workFile = new File(fileName);
					workFile.createNewFile();
					
					return loadFile(list);
				}
				catch (IOException e) 
				{
					System.out.println(e.getMessage());
					return false;
				}
			}
			else
			{
				workFile = new File(defaultFileName);
				return loadFile(list);
			}
		}
	}
	
	private boolean loadFile(List<Tour> list)
	{
		try 
		{
			Scanner scanner = new Scanner(new FileInputStream(workFile));
			Tour tour;
			list.clear();
			
			int count = 0;
			
			while (scanner.hasNextLine())
	        {
				String data = scanner.nextLine();
				
				tour = new Tour();
				count++;
				tour.fillData(data, count);
				
				if (!tour.isCorrect())
				{
					scanner.close();
					return false;
				}
				
				list.add(tour);
	        }
			
			scanner.close();
		}
		catch (IOException e) 
		{
			System.out.println(e.getMessage());
			return false;
		}
		 
		return true;
	}
	
	
	public void saveFile(String fileName, ArrayList<String> data)
	{
		try
		{
			PrintWriter writer = new PrintWriter(fileName, "UTF-8");
			
	        for (String str : data)
	        {
	        	writer.println(str);
	        }
	        
	        writer.close();
		}
		catch (IOException e) 
		{
			System.out.println(e.getMessage());
			System.exit(1);
		}
	}
	
	
	
	
}
